const { playLine } = require("../config/index");

let funList = [
  async function (url, videoUrl) {
    const browser = global.browser;
    const page = await browser.newPage();
    console.log(url + videoUrl);
    // 设置User-Agent 伪装成用户通过浏览器访问： 防止服务器识别出是爬虫请求，会拒绝访问。所以此时设置User-Agent。
    await page.setUserAgent(
      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"
    );
    page.goto(url + videoUrl, { waitUntil: "networkidle2" });
    // 等待页面导航到新 URL 或重新加载。
    await page.waitForNavigation();
    let resUrl = await new Promise((resolve) => {
      // 监听所有请求
      page.on("request", (res) => {
        console.log(res.resourceType(), "----", res.url());
        let url = res.url();
        // 匹配请求类型为media 返回
        if (res.resourceType() === "media") {
          resolve(url);
          return;
        }
        setTimeout(() => {
          resolve(false);
        }, 10000);
      });
    });
    setTimeout(() => {
      page.close();
    }, 60000);
    return resUrl;
  },
  async function (url, videoUrl) {
    const browser = global.browser;
    const page = await browser.newPage();
    await page.setUserAgent(
      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"
    );
    console.log(url + videoUrl);
    page.goto(url + videoUrl, { waitUntil: "networkidle2" });
    await page.waitForNavigation(); // 等待页面跳转
    await page.content();
    let resUrl = await new Promise((resolve) => {
      page.on("response", (res) => {
        console.log("----", res.url());
        let url = res.url();
        let regx = /\.(mp4|m3u8)$/;
        if (regx.test(url)) {
          resolve(url);
          return;
        }
        setTimeout(() => {
          resolve(false);
        }, 10000);
      });
    });
    setTimeout(() => {
      page.close();
    }, 60000);
    return resUrl;
  },
];

module.exports = async (sourceUrl) => {
  for (let i = 0; i < playLine.length; i++) {
    let ele = playLine[i];
    let palyUrl = await funList[ele.type](ele.url, sourceUrl);
    if (palyUrl) {
      return palyUrl;
    }
  }
  return false;
  // let ele = playLine[1];
  // let palyUrl = await funList[ele.type](ele.url, sourceUrl);
  // return palyUrl;
};
